package org.madmatrix.galarm;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ListView;
import android.widget.Switch;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;

public class MainActivity extends Activity {

	/**
	 * 新增闹钟请求码
	 */
	private static final int REQCODE_ADD_ALARM = 1;

	/**
	 * 编辑闹钟请求码
	 */
	private static final int REQCODE_EDIT_ALARM = 2;

	private Gson mGson = new Gson();
	private List<Alarm> mAlarmList = new ArrayList<Alarm>();
	private ListView lvAlarmList;
	private AlarmAdapter mAdapter;
	private Context mContext;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		mContext = this;

		mAlarmList = GAlarmManager.loadAllAlarms(this);
		lvAlarmList = (ListView) findViewById(R.id.alarmlist);
		mAdapter = new AlarmAdapter();
		lvAlarmList.setAdapter(mAdapter);
		lvAlarmList.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
				Intent intent = new Intent(mContext, AddingAlarmActivity.class);
				intent.putExtra("alarm", mGson.toJson(mAdapter.getItem(position)));
				startActivityForResult(intent, REQCODE_EDIT_ALARM);
			}
		});

		// 注册闹钟到期广播
		IntentFilter filter = new IntentFilter();
		filter.addAction(Constants.ACTION_ALARM_EXPIRES);
		LocalBroadcastManager.getInstance(this).registerReceiver(new BroadcastReceiver() {

			@Override
			public void onReceive(Context context, Intent intent) {
				Alarm alarm = mGson.fromJson(intent.getStringExtra("alarm"), Alarm.class);
				mAdapter.editAlarm(alarm);
			}

		}, filter);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.menu_main, menu);

		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case R.id.action_add_alarm:
			Intent intent = new Intent(mContext, AddingAlarmActivity.class);
			startActivityForResult(intent, REQCODE_ADD_ALARM);

			break;
		default:
		}

		return super.onOptionsItemSelected(item);
	}

	private class AlarmAdapter extends BaseAdapter {

		public void addAlarm(Alarm alarm) {
			if (GAlarmManager.addAlarm(mContext, alarm)) {
				mAlarmList.add(alarm);
				notifyDataSetChanged();
				
				Toast.makeText(mContext, GAlarmManager.getAlarmHint(alarm), Toast.LENGTH_SHORT).show();
			} else {
				Toast.makeText(mContext, "添加闹钟失败!", Toast.LENGTH_SHORT).show();
			}
		}

		public void editAlarm(Alarm alarm) {
			if (GAlarmManager.editAlarm(mContext, alarm)) {
				int i = 0;
				for (; i < mAlarmList.size(); ++i) {
					if (alarm.id == mAlarmList.get(i).id) {
						break;
					}
				}

				if (i == mAlarmList.size()) {
					Toast.makeText(mContext, "编辑闹钟出错，找不到闹钟: " + alarm.id, Toast.LENGTH_SHORT).show();
				} else {
					mAlarmList.set(i, alarm);
					mAdapter.notifyDataSetChanged();
				}
				
				if (alarm.isEnabled) {
					Toast.makeText(mContext, GAlarmManager.getAlarmHint(alarm), Toast.LENGTH_SHORT).show();
				}
			} else {
				Toast.makeText(mContext, "编辑闹钟失败!", Toast.LENGTH_SHORT).show();
			}
		}

		public void deleteAlarm(long id) {
			Iterator<Alarm> iter = mAlarmList.iterator();
			while (iter.hasNext()) {
				if (iter.next().id == id) {
					if (GAlarmManager.deleteAlarm(mContext, id)) {
						iter.remove();
						notifyDataSetChanged();
						Toast.makeText(mContext, "删除成功!", Toast.LENGTH_SHORT).show();
					} else {
						Toast.makeText(mContext, "删除闹钟失败!", Toast.LENGTH_SHORT).show();
					}

					return;
				}
			}
		}

		@Override
		public int getCount() {
			return mAlarmList.size();
		}

		@Override
		public Object getItem(int position) {
			return mAlarmList.get(position);
		}

		@Override
		public long getItemId(int position) {
			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			if (null == convertView) {
				convertView = LayoutInflater.from(mContext).inflate(R.layout.listitem_alarm_alarm, null, false);

				ViewHolder holder = new ViewHolder();
				holder.tvTitle = (TextView) convertView.findViewById(R.id.title);
				holder.tvDescription = (TextView) convertView.findViewById(R.id.description);
				holder.tvAlarmId = (TextView) convertView.findViewById(R.id.alarm_id);
				holder.swEnableAlarm = (Switch) convertView.findViewById(R.id.btn_switch);
				holder.vDeleteAlarm = convertView.findViewById(R.id.btn_delete);
				convertView.setTag(holder);

				convertView.findViewById(R.id.btn_delete).setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						final Alarm alarm = (Alarm) v.getTag();

						new AlertDialog.Builder(mContext, R.style.GAlarm_Theme_Holo_Dialog).setTitle("提示")
								.setMessage("确定要删除" + GAlarmManager.getTriggerTime(alarm) + "这个闹钟吗")
								.setPositiveButton("确定", new OnClickListener() {

									@Override
									public void onClick(DialogInterface dialog, int which) {
										mAdapter.deleteAlarm(alarm.id);
									}
								}).setNegativeButton("取消", null).show();
					}
				});

				holder.swEnableAlarm.setOnCheckedChangeListener(new OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
						Alarm alarm = (Alarm) buttonView.getTag();
						// 如果是界面加载，不重置闹钟，如果是用户设置了激活状态，则重置闹钟
						if (!(alarm.isEnabled && isChecked)) {
							GAlarmManager.enableAlarm(mContext, alarm, isChecked);

							if (isChecked) {
								Toast.makeText(mContext, GAlarmManager.getAlarmHint(alarm), Toast.LENGTH_SHORT).show();
							}
						}
					}
				});
			}

			Alarm alarm = mAlarmList.get(position);
			ViewHolder holder = (ViewHolder) convertView.getTag();
			holder.swEnableAlarm.setTag(alarm);
			holder.vDeleteAlarm.setTag(alarm);
			holder.tvAlarmId.setText(alarm.id + "");
			holder.tvTitle.setText(GAlarmManager.getTriggerTime(alarm));
			holder.tvDescription.setText(GAlarmManager.getRepeatDaysDesc(alarm));
			holder.swEnableAlarm.setChecked(alarm.isEnabled);

			return convertView;
		}

	}

	private class ViewHolder {
		public TextView tvAlarmId;
		public TextView tvTitle;
		public TextView tvDescription;
		public Switch swEnableAlarm;
		public View vDeleteAlarm;
	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (Constants.RETCODE_SUCCESS == resultCode) {
			if (null == data) { // 取消新增或编辑
				return;
			}

			switch (requestCode) {
			case REQCODE_ADD_ALARM:
				Alarm newAlarm = mGson.fromJson(data.getStringExtra("alarm"), Alarm.class);
				mAdapter.addAlarm(newAlarm);
				
				break;
			case REQCODE_EDIT_ALARM:
				Alarm alarm = mGson.fromJson(data.getStringExtra("alarm"), Alarm.class);
				mAdapter.editAlarm(alarm);

				break;
			default:
			}
		} else {
			if (REQCODE_ADD_ALARM == requestCode) {
				Toast.makeText(mContext, "新增闹钟失败", Toast.LENGTH_SHORT).show();
			} else if (REQCODE_EDIT_ALARM == requestCode) {
				Toast.makeText(mContext, "修改闹钟失败", Toast.LENGTH_SHORT).show();
			}
		}

		super.onActivityResult(requestCode, resultCode, data);
	}

}
